package android_rteditor.customsortricheditor.editor;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.view.View;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import android_rteditor.customsortricheditor.PhotoPreviewActivity;
import android_rteditor.customsortricheditor.R;
import android_rteditor.customsortricheditor.event.EventCenter;

/**
 * Created by chenxunlin01 on 2017/8/16.
 */

public class RichImage extends android.support.v7.widget.AppCompatImageView implements IEditorItem, View
        .OnClickListener, View.OnLongClickListener {

    private String mUrl;
    private Context mContext;

    public RichImage(Context context) {
        super(context);
        this.mContext = context;
        setBackgroundColor(Color.GREEN);
        setOnClickListener(this);
        setOnLongClickListener(this);
    }

    public RichImage(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RichImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public View getView() {
        return this;
    }

    /**
     * 从网络加载图片
     *
     * @param url url
     */
    public void loadImage(String url) {
        mUrl = url;
        Glide.with(mContext).load(url).error(R.mipmap.ic_launcher).into(this);
    }

    /**
     * 从本地加载图片
     *
     * @param file file
     */
    public void loadImage(File file) {
        mUrl = file.getAbsolutePath();
        Glide.with(mContext).load(file).fitCenter().error(R.mipmap.ic_launcher).into(this);
    }

    @Override
    public int getType() {
        return EditorItemFactory.EDITOR_ITEM_IMAGE;
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(mContext, PhotoPreviewActivity.class);
        intent.putExtra("url", mUrl);
        mContext.startActivity(intent);
    }

    @Override
    public boolean onLongClick(View v) {
        new AlertDialog.Builder(mContext)
                .setTitle("提示")
                .setMessage("确定删除该图片吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EventCenter.ImageDeleteEvent event = new EventCenter.ImageDeleteEvent();
                        event.mUrl = mUrl;
                        event.mRichImage = (RichImage) getView();
                        EventBus.getDefault().post(event);
                        dialog.dismiss();
                    }
                }).show();
        return false;
    }
}
